package com.hippy.erya.modular.erya;

import cn.stylefeng.roses.kernel.model.response.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hippy.erya.base.auth.context.LoginContextHolder;
import com.hippy.erya.base.pojo.page.LayuiPageFactory;
import com.hippy.erya.base.pojo.page.LayuiPageInfo;
import com.hippy.erya.common.DateUtil;
import com.hippy.erya.core.schedue.spring.CostingJob;
import com.hippy.erya.entity.CostingDO;
import com.hippy.erya.impl.CostingServiceImpl;
import com.hippy.erya.modular.util.excel.EasyExcelUtils;
import com.hippy.erya.query.BaseQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.util.Date;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/erya/costing")
public class CostingController {

    @Autowired
    private CostingServiceImpl costingService;

    @RequestMapping(value = "/costing")
    public String costing() {
        return "/erya/costing/costing_setting.html";
    }

    @RequestMapping(value = "/costingEdit")
    public String costingEdit() {
        return "/erya/costing/costing_edit.html";
    }

    @RequestMapping(value = "/costingAdd")
    public String costingAdd() {
        return "/erya/costing/costing_add.html";
    }

    @RequestMapping("/queryAll")
    @ResponseBody
    public LayuiPageInfo queryByPage(@PathParam("page") Long page, @PathParam("limit") int limit,
                                     @PathParam("costingDateRange") String costingDateRange) {
        return LayuiPageFactory.createPageInfo(costingService.queryByPage(page, limit, costingDateRange));
    }

    @RequestMapping("/costingDetail/{id}")
    @ResponseBody
    public ResponseData costingDetail(@PathVariable("id") long id) {
        return ResponseData.success(costingService.queryById(id));
    }

    @RequestMapping("/costingUpdate")
    @ResponseBody
    public ResponseData costingUpdate(CostingDO costingDO) {
        String userId = String.valueOf(LoginContextHolder.getContext().getUserId());
        costingDO.setUpdatedBy(userId);
        costingDO.setUpdatedAt(new Date());
        costingDO.setStatus("1");
        costingDO.setAllProfit(costingDO.getOrderAllIncome() - costingDO.getRawMaterialCost() - costingDO.getArtificialCost()
        - costingDO.getPackageCost() - costingDO.getRelationshipCost() - costingDO.getOperationCost());
        return ResponseData.success(costingService.updateById(costingDO));
    }


    @RequestMapping("/delete/{id}")
    @ResponseBody
    public ResponseData delete(@PathVariable("id") long id) {
        CostingDO costingDO = costingService.queryById(id);
        String userId = String.valueOf(LoginContextHolder.getContext().getUserId());
        costingDO.deleteData(userId);
        costingService.updateById(costingDO);
        return ResponseData.success();
    }

    @RequestMapping("/add")
    @ResponseBody
    public ResponseData add(CostingDO costingDO) {
        String userId = String.valueOf(LoginContextHolder.getContext().getUserId());
        CostingDO costingDO1 = costingService.queryByOrderDate(costingDO.getCostingDate(), userId);
        if (costingDO1 != null) {
            return ResponseData.error("该日期已存在核算数据!");
        }
        costingDO.setCreatedBy(userId);
        costingDO.setUpdatedBy(userId);
        costingDO.setUserCode(userId);
        costingDO.setStatus("1");
        costingService.insert(costingDO);
        return ResponseData.success();
    }

    @GetMapping("/downLoad")
    public void downLoad(@RequestParam("dateRange") String dateRange,
                         HttpServletResponse response) {
        try {
            QueryWrapper<CostingDO> queryWrapper = BaseQueryWrapper.buildQuery();
            BaseQueryWrapper.buildQuery(queryWrapper, dateRange, "COSTING_DATE");
            List<CostingDO> costingDOS = costingService.getBaseMapper().selectList(queryWrapper);
            costingDOS.forEach(costingDO -> {
                String status = costingDO.getStatus();
                costingDO.setStatus(StringUtils.isEmpty(status) || "0".equals(status) ? "未核算" : "已核算");
            });
            EasyExcelUtils.write(costingDOS, CostingDO.class, "核算数据.xlsx", "核算数据", response);
        } catch (Exception e) {
            log.error("平台数据文件下载失败", e);
        }
    }

    @Autowired
    private CostingJob costingJob;


    @RequestMapping("/costingHistoryOrder")
    @ResponseBody
    public ResponseData delete() {
        Date currentDate = DateUtil.getCurrentDate();
        String userId = String.valueOf(LoginContextHolder.getContext().getUserId());
        for (int i = 1; i < 30; i++) {
            Date orderDate = DateUtil.plusDays(currentDate, -1 * i);
            CostingDO costingDO = costingService.queryByOrderDate(orderDate, userId);
            if (costingDO != null) {
                continue;
            }
            costingJob.costingOrderDetail(orderDate, userId);
        }
        return ResponseData.success();
    }



}
